package com.fzu.ess.ess.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fzu.ess.common.Const;
import com.fzu.ess.common.Model.FilterRule;
import com.fzu.ess.common.Model.JsonModel;
import com.fzu.ess.common.utils.SearchUtils;
import com.fzu.ess.ess.dao.BookDao;
import com.fzu.ess.ess.entity.Book;
import com.fzu.ess.ess.entity.Language;
import com.fzu.ess.ess.service.BookService;
import com.fzu.ess.sys.entity.Message;
import com.fzu.ess.sys.entity.User;
import com.fzu.ess.sys.service.MessageService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by ercha on 2015/10/25.
 */
@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookDao bookDao;

    @Autowired
    private HttpSession session;

    @Autowired
    private MessageService messageService;

    @Override
    public Book getById(String id) {
        try{
            if(id==null || id.length()<1){
                return null;
            }
            return bookDao.get(Book.class, id);
        } catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String create(Book book) {
        try {
            return (String) bookDao.save(book);
        } catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<Book> getAll() {
        try{
            return bookDao.find("from Book b where b.delFlag = " + Const.DEL_FLAG_NORMAL);
        } catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public JsonModel getDataByPage(Integer pageNumber, Integer pageSize, String filterText) {
        JsonModel j = new JsonModel();

        StringBuilder hqlData = new StringBuilder("from Book b where ");
        String hqlCount;

        if(filterText!=null && filterText.length()>1){
//            System.out.println("filterText: " + filterText);
//            hqlData.append("where ");
            hqlData.append(SearchUtils.getSearchStr(filterText, "b"));
//            System.out.println("hql: " + hqlData.toString());
            hqlData.append(" and ");
        }

        hqlData.append(" b.delFlag = " + Const.DEL_FLAG_NORMAL + " order by b.createDate desc ");

        if(pageNumber==null || pageNumber<0){
            pageNumber = 0;
        }

        if(pageSize==null || pageSize<0){
            pageSize = 0;
        }

        System.out.println("hql: " + hqlData.toString());
        hqlCount = "select count(*) " + hqlData.toString();
        try {
            List<Book> bl = bookDao.find(hqlData.toString(), pageNumber, pageSize);
            j.setDataObj(bl);
            j.setTotal(bookDao.count(hqlCount));
            j.setRows(bl.size());
            return j;
        } catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 只有用户上下架，管理员是删除
     * @param bookId
     * @param userId
     * @param currentStatus
     * @return
     */
    @Override
    public JsonModel toggleStatus(String bookId, String userId, Integer currentStatus) {
        JsonModel j = new JsonModel();
        if(currentStatus==null || currentStatus>1){
            return j;
        }
        currentStatus ^= 1;
        User user = (User)session.getAttribute(Const.SESSION.USER);
        int res = 0;
        if(user.getId().equals(userId)){
            res = bookDao.executeHql("update Book b set b.status = " + currentStatus + " where b.id = '"
                    + bookId +"' and b.owner.id = '" + userId + "'");
        }
        j.setSuccess(res > 0);
        return j;
    }

    @Override
    public JsonModel update(Book book, String language, String images) {
        JsonModel jsonModel = new JsonModel();
        List<String> imageList = new ArrayList<>();
        try {
            if(images!=null && images.length()>1){
                imageList = JSON.parseObject(images, new TypeReference<List<String>>() {
                });
            }

            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            User user = (User)session.getAttribute(Const.SESSION.USER);

            book.setOwner(user);
            book.setBookLanguage(new Language(language));
            book.setImageList(imageList);
            bookDao.update(book);
            jsonModel.setSuccess(true);
        } catch(Exception e){
            e.printStackTrace();
        }
        return jsonModel;
    }

    @Override
    public JsonModel deleteByUser(String bookId, String userId) {
        JsonModel j = new JsonModel();
        User user = (User)session.getAttribute(Const.SESSION.USER);
        if(!user.getId().equals(userId)){
            return j;
        }
        try {
            int ret =bookDao.executeHql("update Book b set b.delFlag = " + Const.DEL_FLAG_DELETED
                    + "where b.id = '" + bookId + "' and b.owner.id = '" + userId + "'");
            j.setSuccess(ret > 0);

        } catch (Exception e){
            e.printStackTrace();
        }
        return j;
    }

    @Override
    public JsonModel deleteByAdmin(String bookId, String reason) {
        JsonModel j = new JsonModel();
        User admin = (User)session.getAttribute(Const.SESSION.USER);
        try {
            boolean res;
            bookDao.executeHql("update Book b set b.delFlag = " + Const.DEL_FLAG_DELETED
                    + "where b.id = '" + bookId + "'");

            //给书籍的主人发送系统消息
            Book book = bookDao.get(Book.class, bookId);
            res = messageService.deleteBookMessage(admin.getId(), book.getOwner().getId(), reason);
            if(!res){
                j.setMsg("发送通知消息失败！");
            }
            j.setSuccess(res);
        } catch (Exception e){
            e.printStackTrace();
        }
        return j;
    }

}
